package com.grandtech.insurance.dao.app;

import com.grandtech.insurance.common.db.utils.ReflectionUtils;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Field;
import java.util.List;

@Repository
public class MongoDaoImpl<T> implements MongoDao<T> {


    /**
     * spring mongodb　集成操作类
     */
    @Autowired
    protected MongoTemplate mongoTemplate;


    @Override
    public void setMongoTemplate(MongoTemplate template) {
        if (template != null) {
            this.mongoTemplate = template;
        }
    }

    @Override
    public boolean existCollect(String collectName) {
        //2019-05-28，mongo驱动版本升级修改集合存在方法
        MongoIterable<String> iterable = mongoTemplate.getDb().listCollectionNames();
        try (final MongoCursor<String> it = iterable.iterator()) {
            while (it.hasNext()) {
                if (it.next().equalsIgnoreCase(collectName)) {
                    return true;
                }
            }
        }
        return false;

        //return mongoTemplate.getDb().collectionExists(collectName);
    }

    @Override
    public boolean existIndex(String collectName, String index) {
        if (index == null || index.equals("")) return false;
        boolean existCollect = existCollect(collectName);
        if (!existCollect) return existCollect;

        //2019-05-28，mongo驱动版本升级修改查询索引方法
        ListIndexesIterable<Document> indexes = mongoTemplate.getDb().getCollection(collectName).listIndexes();
        for (Document docIndex : indexes) {
            if (docIndex.get("name").equals(index)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean createCollect(T entity, String collectName) {
        //2019-05-28，mongo驱动版本升级修改创建集合方法
        mongoTemplate.createCollection(collectName);
        return true;
    }

    @Override
    public boolean createCollect(String collectName) {
        mongoTemplate.createCollection(collectName);
        return true;
    }

    @Override
    public boolean createIndex(Class clazz, String collectName) {
        return false;
    }


    @Override
    public void insert(T entity) {
        mongoTemplate.insert(entity);
    }

    @Override
    public void insert(T entity, String collectName) {
        mongoTemplate.insert(entity, collectName);
    }

    @Override
    public void insert(List<T> list, Class clazz) {
        mongoTemplate.insert(list, clazz);
    }

    @Override
    public void insert(List<T> list, String collectName) {
        mongoTemplate.insert(list, collectName);
    }

    public T save(T entity) {
        mongoTemplate.save(entity);
        return entity;
    }

    @Override
    public void saveOrUpdate(T entity, Query query, String collectName) {
        boolean flag = mongoTemplate.exists(query, collectName);
        if (flag) {
            mongoTemplate.remove(query, collectName);
        }
        save(entity, collectName);
    }

    @Override
    public T save(T entity, String collectName) {
        mongoTemplate.save(entity, collectName);
        return entity;
    }


    @Override
    public void save(List<T> list, String collectName) {
        mongoTemplate.save(list, collectName);
    }


    public T findById(String id) {
        return mongoTemplate.findById(id, this.getEntityClass());
    }


    public T findById(String id, String collectionName) {
        return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
    }

    @Override
    public T findTByQuery(Query query, Class clazz, String collectionName) {
        return (T) mongoTemplate.findOne(query, clazz, collectionName);
    }

    @Override
    public T findTByQuery(Query query, Class clazz) {
        return (T) mongoTemplate.findOne(query, clazz);
    }

    public List<T> findAll() {
        return mongoTemplate.findAll(this.getEntityClass());
    }


    public List<T> findAll(String collectionName) {
        return mongoTemplate.findAll(this.getEntityClass(), collectionName);
    }


    public List<T> find(Query query) {
        return mongoTemplate.find(query, this.getEntityClass());
    }


    public T findOne(Query query) {
        return mongoTemplate.findOne(query, this.getEntityClass());
    }


    public Page<T> findPage(Page<T> page, Query query) {
        return page;
    }


    public long count(Query query) {
        return mongoTemplate.count(query, this.getEntityClass());
    }


    public UpdateResult update(Query query, Update update) {
        if (update == null) {
            return null;
        }
        return mongoTemplate.updateMulti(query, update, this.getEntityClass());
    }


    public T updateOne(Query query, Update update) {
        if (update == null) {
            return null;
        }
        return mongoTemplate.findAndModify(query, update, this.getEntityClass());
    }


    public UpdateResult update(T entity) {
        Field[] fields = this.getEntityClass().getDeclaredFields();
        if (fields == null || fields.length <= 0) {
            return null;
        }
        Field idField = null;
        // 查找ID的field
        for (Field field : fields) {
            if (field.getName() != null && "id".equals(field.getName().toLowerCase())) {
                idField = field;
                break;
            }
        }
        if (idField == null) {
            return null;
        }
        idField.setAccessible(true);
        String id = null;
        try {
            id = (String) idField.get(entity);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (id == null || "".equals(id.trim()))
            return null;
        // 根据ID更新
        Query query = new Query(Criteria.where("_id").is(id));
        // 更新
        // Update update = new Update();
        // for (Field field : fields) {
        // // 不为空 不是主键 不是序列化号
        // if (field != null
        // && field != idField
        // && !"serialversionuid"
        // .equals(field.getName().toLowerCase())) {
        // field.setAccessible(true);
        // Object obj = field.get(entity);
        // if (obj == null)
        // continue;
        // update.set(field.getName(), obj);
        // }
        // }
        Update update = ReflectionUtils.getUpdateObj(entity);
        if (update == null) {
            return null;
        }
        return mongoTemplate.updateFirst(query, update, getEntityClass());
    }


    public void remove(Query query) {
        mongoTemplate.remove(query, this.getEntityClass());
    }


    /**
     * 获得泛型类
     */
    private Class<T> getEntityClass() {
        return ReflectionUtils.getSuperClassGenricType(getClass());
    }
}









